package tools;

import model.Department;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class IODataTool{

    public static String pathname ="D:\\Java\\workspaces\\zhiyou100\\day38_test\\resources\\department.txt";

    // 声明一个读方法
    public static List<Department> readData() {
        // 通过对象序列化流 文件字节流
        List<Department> departmentList = null;
        try {
            FileInputStream fis = new FileInputStream(pathname);
            ObjectInputStream ois = new ObjectInputStream(fis);
            departmentList = (List<Department>) ois.readObject();// EOFException
        } catch (Exception e) {
            System.out.println("流中无数据");
        }
        return departmentList;
    }

    // 声明一个写方法
    public static void writeData(Department department,String operation){ // Object  add/edit/delete
        try {
            // 先从流中把数据读出来
            List<Department> departments = readData();
            if (departments == null) {
                departments = new ArrayList<>();
            }
            // 编辑还是添加  添加
            if (operation.equals("add")) {
                departments.add(department);
            } else if (operation.equals("edit")){
                // 遍历  通过id
                for (int i = 0; i < departments.size(); i++) {
                    // 判断
                    if (departments.get(i).getdId().equals(department.getdId())) {
                        departments.set(i, department);
                        break;
                    }
                }
            } else if (operation.equals("delete")) {
                // 遍历  通过id
                for (int i = 0; i < departments.size(); i++) {
                    // 判断
                    if (departments.get(i).getdId().equals(department.getdId())) {
                        departments.remove(i);
                        break;
                    }
                }
            }
            System.out.println("+++++"+departments);
            // 文件字节输出流
            FileOutputStream fos = new FileOutputStream(pathname);
            // 通过对象序列化流
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(departments);
        } catch (Exception e) {
            System.out.println("写数据有异常");
            System.out.println(e.getCause());
        }

    }
}
